package com.adong.crowd.mvc.handler;

import com.adong.crowd.entity.Menu;
import com.adong.crowd.mapper.MenuMapper;
import com.adong.crowd.service.api.MenuService;
import com.adong.crowd.util.ResultEntity;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.midi.Soundbank;
import java.util.HashMap;
import java.util.List;

@RestController
public class MenuHandler {

    @Autowired
    private MenuService menuService;


    // 获取全部Menu对象
    @RequestMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getWhileTreeNew() {
        // 查询全部的Menu对象
        List<Menu> menuList = menuService.getAll();

        // 声明存储的变量来存储找到的根节点
        Menu root = null;

        // 创建Map对象来存储id和Menu对象的对应关系便于查找父节点
        HashMap<Integer, Menu> menuMap = new HashMap<>();

        // 遍历menuList填充menuMap
        for (Menu menu : menuList) {
            Integer id = menu.getId();
            menuMap.put(id, menu);
        }

        // 遍历menuList查找根节点,组装父节点
        for (Menu menu : menuList) {
            // 获取当前menu对象的pid
            Integer pid = menu.getPid();

            // pid为null,判断为根节点
            if (pid == null) {
                root = menu;
                // 当前节点是根节点,肯定没有父节点,不必继续执行
                continue;
            }

            // 不为null,当前节点有父节点
            Menu father = menuMap.get(pid);

            // 将当前节点出入父节点的children集合中
            father.getChildren().add(menu);

        }

        // 经过上面的运算,根节点包含了整个树形结构,返回节点就是整个树
        return ResultEntity.successWithData(root);
    }

    /**
     * 保存菜单节点的数据
     *
     * @return
     */
    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu) {

        System.out.println(menu);

        menuService.save(menu);
        return ResultEntity.successWithoutData();
    }


    @RequestMapping("menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu) {
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("menu/remove.json")
    public ResultEntity<String> removeMenu(Integer id) {
        menuService.remove(id);
        return ResultEntity.successWithoutData();
    }

}
